<template>
  <div class="tag-factory analyse-similar">
    <factory-config-list
      ref="factoryConfigList"
      :preview="false"
      @addItem="addItem"
      @clearConfig="clearConfig"
    ></factory-config-list>
    <div class="factory-content" v-loading="loading">
      <el-row :gutter="20">
        <el-col :span="6" align="left">
          <div class="factory-top">
            <h2>
              <icon-svg name="iconRole" slot="prefix"></icon-svg>
              相似人群扩展
            </h2>
          </div>
        </el-col>
        <el-col :span="18" align="right">
          <div class="btns">
            <el-button @click="clear">
              <icon-svg name="iconCancel"></icon-svg>
              取消
            </el-button>
            <el-button type="primary" @click="handlePreview">
              <icon-svg name="iconFacEye"></icon-svg>
              预览
            </el-button>
            <el-button type="primary" @click="submit">
              <icon-svg name="iconSave"></icon-svg>
              保存
            </el-button>
          </div>
        </el-col>
      </el-row>
      <div class="similar-wrapper tag-scrollbar">
        <div class="section-title">
          <i :class="showLogic ? 'el-icon-caret-bottom' : 'el-icon-caret-right'" @click="showLogic = !showLogic"></i>
          {{ isSeed ? '种子人群配置' : '目标人群配置' }}
          <span class="title-switch">
            <el-switch
              active-color="#13ce66"
              inactive-color="#455fbc"
              v-model="isSeed"
              active-text="种子人群配置"
              inactive-text="目标人群配置"
            >
            </el-switch>
          </span>
        </div>
        <el-collapse-transition>
          <div class="section-content" v-show="showLogic">
            <el-form :model="editForm" ref="editForm" label-width="0">
              <similar-logic
                ref="sourceLogic"
                :derivedTagData="editForm.tagSourceJson"
                formProp="tagSourceJson"
                v-show="isSeed"
              ></similar-logic>
              <div v-show="!isSeed">
                <div class="target-content">
                  <el-row :gutter="20">
                    <el-col :span="12">
                      <div class="source-item">
                        <div class="star"></div>
                        <div class="source-title linear-purpose">剔除种子人群</div>
                        <div class="source-content">
                          <el-form-item prop="eliminateSeedPeople">
                            <el-switch
                              active-color="#74c4b9"
                              v-model="editForm.eliminateSeedPeople"
                              active-text="是"
                              inactive-text="否"
                            >
                            </el-switch>
                          </el-form-item>
                        </div>
                      </div>
                    </el-col>
                    <el-col :span="12">
                      <div class="source-item">
                        <div class="star"></div>
                        <div class="source-title linear-purpose">种子人群抽样比例</div>
                        <div class="source-content">
                          <el-form-item
                            prop="sampleRate"
                            :rules="[{ required: true, message: '抽样比例不能为空', trigger: 'change' }]"
                          >
                            <el-select v-model="editForm.sampleRate" placeholder="请选择种子人群抽样比例">
                              <el-option label="---" value=""></el-option>
                              <el-option label="全部" value="1/1"></el-option>
                              <el-option v-for="item in sampleList" :key="item" :label="item" :value="item"></el-option>
                            </el-select>
                          </el-form-item>
                        </div>
                      </div>
                    </el-col>
                  </el-row>
                </div>
                <similar-logic
                  ref="targetLogic"
                  :derivedTagData="editForm.tagTargetJson"
                  formProp="tagTargetJson"
                ></similar-logic>
              </div>
            </el-form>
          </div>
        </el-collapse-transition>
        <div class="section-title">
          <i :class="showResult ? 'el-icon-caret-bottom' : 'el-icon-caret-right'" @click="showResult = !showResult"></i>
          结果预览
        </div>
        <el-collapse-transition>
          <div class="section-content" v-show="showResult">
            <el-row :gutter="20" class="result-title">
              <el-col :span="12" align="center">
                <span>种子人群命中客户数（人）</span>
              </el-col>
              <el-col :span="12" align="center">
                <span>目标人群命中客户数（人）</span>
              </el-col>
            </el-row>
            <el-row :gutter="20" class="result-content">
              <el-col :span="12">
                <el-row :gutter="20">
                  <el-col :span="12" align="center">
                    <tag-progress
                      type="circle"
                      :percentage="editForm.sourceCustRate"
                      :behindStrokeWidth="5"
                      :gapWidth="2"
                      stroke-linecap="square"
                      color="#007aff"
                      bebindColor="#e9f0f7"
                      class="quality-progress"
                      :width="100"
                    >
                      <div slot="content" class="quality-inner-text">
                        <p>{{ editForm.sourceCustRate }}%</p>
                      </div>
                    </tag-progress>
                  </el-col>
                  <el-col :span="12" align="center">
                    <span class="count">{{ editForm.sourceCustNum }}</span>
                    <br />
                    在全部用户中占比{{ editForm.sourceCustRate }}%
                  </el-col>
                </el-row>
              </el-col>
              <el-col :span="12">
                <el-row :gutter="20">
                  <el-col :span="12" align="center">
                    <tag-progress
                      type="circle"
                      :percentage="editForm.targetCustRate"
                      :behindStrokeWidth="5"
                      :gapWidth="2"
                      stroke-linecap="square"
                      color="#007aff"
                      bebindColor="#e9f0f7"
                      class="quality-progress"
                      :width="100"
                    >
                      <div slot="content" class="quality-inner-text">
                        <p>{{ editForm.targetCustRate }}%</p>
                      </div>
                    </tag-progress>
                  </el-col>
                  <el-col :span="12" align="center">
                    <span class="count">{{ editForm.targetCustNum }}</span>
                    <br />
                    在全部用户中占比{{ editForm.targetCustRate }}%
                  </el-col>
                </el-row>
              </el-col>
            </el-row>
          </div>
        </el-collapse-transition>
      </div>
    </div>
    <similar-drawer ref="similarDrawer" @callback="setConfig"></similar-drawer>
  </div>
</template>

<script>
import factoryConfigList from '@/views/modules/factory/factory-config-list'
import similarLogic from './similar-logic'
import similarDrawer from './similar-drawer'
import Logic from './similar-config.js'
import cloneDeep from 'lodash/cloneDeep'
export default {
  components: {
    factoryConfigList,
    similarLogic,
    similarDrawer
  },
  data() {
    return {
      loading: false,
      showLogic: true,
      isSeed: true,
      showResult: false,
      oldConfig: {},
      sampleList: ['1/2', '1/4', '1/8', '1/16', '1/32', '1/64', '1/128'],
      editForm: {
        tagId: '',
        groupId: '',
        tagNm: '',
        tagStory: '',
        eliminateSeedPeople: false,
        sampleRate: '',
        featureType: 1,
        featureValue: '',
        execFrequency: '',
        execDtList: [],
        execWkList: [],
        execTm: '',
        tagSourceJson: {
          logicalOperation: 'and',
          tagList: []
        },
        tagTargetJson: {
          logicalOperation: 'and',
          tagList: []
        },
        sourceCustNum: '',
        sourceCustRate: 0,
        targetCustNum: '',
        targetCustRate: 0,
        previewResults: []
      }
    }
  },
  mounted() {
    this.$nextTick(() => {
      if (this.$route.query.tagId) {
        this.editForm.tagId = this.$route.query.tagId
        this.getDetail()
      }
      if (this.$route.query.groupId) this.editForm.groupId = this.$route.query.groupId
    })
  },
  methods: {
    clearConfig() {
      this.editForm.tagSourceJson = {
        logicalOperation: 'and',
        tagList: []
      }
      this.editForm.tagTargetJson = {
        logicalOperation: 'and',
        tagList: []
      }
      this.editForm.sampleRate = ''
      this.editForm.sourceCustNum = ''
      this.editForm.sourceCustRate = 0
      this.editForm.targetCustNum = ''
      this.editForm.targetCustRate = 0
      this.editForm.previewResults = []
      this.showLogic = true
    },
    getDetail() {
      this.$ajax({
        url: this.$ajax.setUrl(`der/derCustExtension/getExtensionDetail/${this.editForm.tagId}`),
        method: 'get',
        params: this.$ajax.setParams()
      }).then(({ data }) => {
        if (data && data.code === '0') {
          this.editForm.tagNm = data.data.tagNm
          this.editForm.tagStory = data.data.tagStory
          this.editForm.eliminateSeedPeople = data.data.eliminateSeedPeople
          this.editForm.sampleRate = data.data.sampleRate
          this.editForm.featureType = data.data.featureType
          this.editForm.featureValue = data.data.featureValue
          this.editForm.execFrequency = data.data.execFrequency
          this.editForm.execDtList = JSON.parse(data.data.execDtList)
          this.editForm.execWkList = JSON.parse(data.data.execWkList)
          this.editForm.execTm = data.data.execTm
          this.editForm.sourceCustNum = data.data.sourceCustNum
          this.editForm.sourceCustRate = data.data.sourceCustRate
          this.editForm.targetCustNum = data.data.targetCustNum
          this.editForm.targetCustRate = data.data.targetCustRate
          const sourceJson = JSON.parse(data.data.tagSourceJson)
          const targetJson = JSON.parse(data.data.tagTargetJson)
          this.editForm.tagSourceJson.logicalOperation = sourceJson.request.labGrps.logicTyp || 'and'
          this.editForm.tagSourceJson.tagList = Logic.initLogic(
            sourceJson.request.labGrps.labs ? sourceJson.request.labGrps.labs : [],
            data.data.baseTags
          )
          this.editForm.tagTargetJson.logicalOperation = targetJson.request.labGrps.logicTyp || 'and'
          this.editForm.tagTargetJson.tagList = Logic.initLogic(
            targetJson.request.labGrps.labs ? targetJson.request.labGrps.labs : [],
            data.data.baseTags
          )
          if (sourceJson.catalogClassId) this.$refs.factoryConfigList.changeCatalogClass(sourceJson.catalogClassId)
          this.showLogic = false
          this.showResult = true
          this.oldConfig = cloneDeep(this.editForm)
        } else {
          // 失败后执行的操作
        }
      })
    },
    addItem(item) {
      if (this.showLogic) {
        if (this.isSeed) this.$refs.sourceLogic.addItem(item)
        else this.$refs.targetLogic.addItem(item)
      }
    },
    handlePreview() {
      this.$refs.editForm.validate(valid => {
        if (valid) {
          this.loading = true
          this.$ajax({
            url: this.$ajax.setUrl('der/derCustExtension/previewCustProportion'),
            method: 'post',
            data: this.$ajax.setData({
              eliminateSeedPeople: this.editForm.eliminateSeedPeople,
              sampleRate: this.editForm.sampleRate,
              tagSourceJson: JSON.stringify(Logic.initParams(this.editForm.tagSourceJson)),
              tagTargetJson: JSON.stringify(Logic.initParams(this.editForm.tagTargetJson))
            })
          }).then(({ data }) => {
            if (data && data.code === '0') {
              this.editForm.sourceCustNum = data.data.sourceCustNum
              this.editForm.sourceCustRate = data.data.sourceCustRate
              this.editForm.targetCustNum = data.data.targetCustNum
              this.editForm.targetCustRate = data.data.targetCustRate
              this.showLogic = false
              this.showResult = true
              this.oldConfig = cloneDeep(this.editForm)
              this.$message.success(data.msg)
            } else {
              this.$message.error(data.data || data.msg)
            }
            this.loading = false
          })
        } else {
          this.$message.info('必填项不能为空')
        }
      })
    },
    setConfig(data) {
      this.editForm.tagId = data.tagId
      this.editForm.tagNm = data.tagNm
      this.editForm.tagStory = data.tagStory
      this.editForm.featureType = data.featureType
      this.editForm.featureValue = data.featureValue
      this.editForm.execFrequency = data.execFrequency
      this.editForm.execDtList = data.execDtList
      this.editForm.execWkList = data.execWkList
      this.editForm.execTm = data.execTm
      this.oldConfig = cloneDeep(this.editForm)
    },
    submit() {
      if (!this.$utils.compareObject(this.oldConfig, this.editForm)) {
        this.$message.info('逻辑配置有变化，请先预览再保存！')
        return
      }
      this.$refs.editForm.validate(valid => {
        if (valid) {
          const tagSourceJson = Logic.initParams(this.editForm.tagSourceJson)
          tagSourceJson.catalogClassId = this.$refs.factoryConfigList.getCatalogClass()
          let params = {
            tagNm: this.editForm.tagNm,
            tagStory: this.editForm.tagStory,
            eliminateSeedPeople: this.editForm.eliminateSeedPeople,
            sampleRate: this.editForm.sampleRate,
            featureType: this.editForm.featureType,
            featureValue: this.editForm.featureValue,
            execFrequency: this.editForm.execFrequency,
            execDtList: this.editForm.execDtList,
            execWkList: this.editForm.execWkList,
            execTm: this.editForm.execTm,
            tagSourceJson: JSON.stringify(tagSourceJson),
            tagTargetJson: JSON.stringify(Logic.initParams(this.editForm.tagTargetJson)),
            sourceCustNum: this.editForm.sourceCustNum,
            sourceCustRate: this.editForm.sourceCustRate,
            targetCustNum: this.editForm.targetCustNum,
            targetCustRate: this.editForm.targetCustRate,
            previewResults: JSON.stringify(this.editForm.previewResults)
          }
          if (this.editForm.tagId) params.tagId = this.editForm.tagId
          if (this.editForm.groupId) params.groupId = this.editForm.groupId
          this.$refs.similarDrawer.showDrawer(params)
        }
      })
    },
    clear() {
      this.$confirm('确定取消最新配置？').then(() => {
        const config = cloneDeep(this.oldConfig)
        if (config.tagId) {
          this.editForm.tagNm = config.tagNm
          this.editForm.tagStory = config.tagStory
          this.editForm.eliminateSeedPeople = config.eliminateSeedPeople
          this.editForm.sampleRate = config.sampleRate
          this.editForm.featureType = config.featureType
          this.editForm.featureValue = config.featureValue
          this.editForm.execFrequency = config.execFrequency
          this.editForm.execDtList = config.execDtList
          this.editForm.execWkList = config.execWkList
          this.editForm.execTm = config.execTm
          this.editForm.tagSourceJson = config.tagSourceJson
          this.editForm.tagTargetJson = config.tagTargetJson
          this.editForm.sourceCustNum = config.sourceCustNum
          this.editForm.sourceCustRate = config.sourceCustRate
          this.editForm.targetCustNum = config.targetCustNum
          this.editForm.targetCustRate = config.targetCustRate
        } else {
          this.editForm.tagNm = ''
          this.editForm.tagStory = ''
          this.editForm.eliminateSeedPeople = false
          this.editForm.sampleRate = ''
          this.editForm.featureType = 1
          this.editForm.featureValue = ''
          this.editForm.execFrequency = ''
          this.editForm.execDtList = []
          this.editForm.execWkList = []
          this.editForm.execTm = ''
          this.editForm.tagSourceJson = {
            logicalOperation: 'and',
            tagList: []
          }
          this.editForm.tagTargetJson = {
            logicalOperation: 'and',
            tagList: []
          }
          this.editForm.sourceCustNum = ''
          this.editForm.sourceCustRate = 0
          this.editForm.targetCustNum = ''
          this.editForm.targetCustRate = 0
        }
      })
    }
  }
}
</script>

<style lang="scss">
.analyse-similar {
  .factory-top {
    line-height: 50px;
    color: $theme-color;
    svg {
      margin-right: 10px;
    }
  }
  .factory-content {
    background-color: #fff;
  }
  .similar-wrapper {
    height: calc(100% - 60px);
    overflow-x: hidden;
    overflow-y: auto;
  }
  .section-title {
    font-size: 18px;
    font-weight: bold;
    height: 80px;
    padding: 20px;
    line-height: 40px;
    color: #1e3592;
    background-color: #c0d2f6;
    border-top-left-radius: 5px;
    border-top-right-radius: 5px;
    i {
      cursor: pointer;
    }
    .title-switch {
      float: right;
      font-size: 14px;
      font-weight: normal;
      color: #4a5593;
      margin-left: 10px;
      cursor: pointer;
    }
  }
  .section-content {
    margin-bottom: 10px;
    border: 1px solid #f5f6f7;
    & + .section-title {
      margin-top: 10px;
    }
  }
  .result-title {
    font-weight: bolder;
    height: 60px;
    border-bottom: 1px solid #eee;
    span {
      display: inline-block;
      width: 80%;
      height: 40px;
      line-height: 40px;
      margin: 10px 0 10px 0;
      background-color: #fcf5e5;
      border-radius: 20px;
    }
  }
  .result-content {
    margin-top: 20px;
    padding-bottom: 10px;
    .count {
      display: inline-block;
      font-size: 25px;
      font-weight: bold;
      color: #f4942b;
      margin: 20px 0;
    }
    & > .el-col {
      padding: 0 10% !important;
    }
  }
  .target-content {
    padding: 20px 20px 0 20px;
  }
  .source-item {
    width: 100%;
    height: 45px;
    margin-bottom: 20px;
    box-shadow: #eee 0 0 10px;
    position: relative;
    .source-title {
      font-weight: bold;
      width: 250px;
      padding-left: 50px;
      line-height: 45px;
      color: #fff;
      position: absolute;
      &:before {
        width: 10px;
        height: 10px;
        content: '';
        background-color: #eee9ff;
        border: 2px solid #cfc7ee;
        margin-top: -5px;
        position: absolute;
        top: 50%;
        left: 20px;
        border-radius: 50%;
      }
      &:after {
        width: 0;
        height: 0;
        content: '';
        margin-top: -10px;
        border-top: 10px solid transparent;
        border-bottom: 10px solid transparent;
        position: absolute;
        top: 50%;
        right: -10px;
      }
      &.linear-purpose:after {
        border-left: 10px solid #7c6bed;
      }
    }
    .source-content {
      line-height: 45px;
      padding: 0 30px 0 280px;
      white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
    }
    .el-select {
      width: 100%;
      .el-input__inner {
        border: 0;
      }
    }
  }
}
</style>
